<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button type="warning" size="small" @click="uploadInput = true">导入excel</el-button>
          <el-button type="danger" size="small" @click="hExport">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工
          </el-button>
        </template>
      </PageTools>
      <el-card style="margin-top: 10px;">
        <el-table border :data="List">
          <el-table-column label="序号" type="index" :index="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <image-holder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template slot-scope=" scope ">
              {{ forMat(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="correctionTime" />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/'+scope.row.id)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="pageParams.page"
            :page-sizes="[1, 2, 3, 4,10]"
            :page-size="pageParams.size"
            @current-change="hCurrentChange"
            @size-change="handleSizeChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工 -->
      <el-dialog
        v-if="showDialog"
        :visible.sync="showDialog"
        title="新增员工"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <addorEdit
          @close="showDialog=false"
          @updateEmpolyee="hUpdateEmpolyee"
        />
      </el-dialog>
      <!-- 导入excel -->
      <el-dialog
        :visible.sync="uploadInput"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <UploadExcel :on-success="handleSuccess" />
      </el-dialog>
    </div>
  </div>
</template>
<script>

import { getEmployeeList, delEmployee, importEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import addorEdit from './empDialog.vue'
import UploadExcel from '@/components/UploadExcel/index.vue'
import { formatExcelDate } from '@/utils/index.js'
// EmployeeEnum.hireType: [{id:1,value:'正式'}，{id:2,value:'非正式'}]
const obj = EmployeeEnum.hireType.reduce((acc, cur) => {
  acc[cur.id] = cur.value
  return acc
}, {})
export default {
  components: {
    addorEdit,
    UploadExcel
  },
  data() {
    return {
      pageParams: {
        page: 1, // 查询第一页
        size: 10 // 每页两条  --- 要与pagination中page-size一致
      },
      List: [],
      total: 0,
      showDialog: false,
      uploadInput: false
    }
  },
  computed: {
    index() {
      return (this.pageParams.page - 1) * this.pageParams.size + 1
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    forMat(typeNum) {
      return obj[typeNum]
    },
    async loadEmployeeList() {
      const res = await getEmployeeList(this.pageParams)
      console.log(res)
      this.List = res.data.rows
      this.total = res.data.total
    },
    hCurrentChange(curPage) {
      // alert(curPage)
      // 1. 更新页码
      this.pageParams.page = curPage
      // 2. 重发请求
      this.loadEmployeeList()
    },
    handleSizeChange(val) {
      this.pageParams.size = val
      // 2. 重发请求
      this.loadEmployeeList()
    },
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        console.log('delEmployee', res)
        // 重发请求
        if (this.List.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }
        this.loadEmployeeList()
      } catch (err) {
        console.log('delEmployee', err)
      }
    },

    hDel(id) {
      console.log(id)
      this.$confirm('确认删除吗？').then(() => {
        this.doDel(id)
      }).catch(() => {})
    },
    hUpdateEmpolyee() {
      this.showDialog = false
      this.pageParams.page = Math.ceil(++this.total / this.pageParams.size)
      this.loadEmployeeList()
    },

    // 导入excel
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    async doImport(data) {
      try {
        const res = await importEmployee(data)
        console.log(res)
        this.$message.success('导入成功')
        this.loadEmployeeList()
      } catch (err) {
        this.$message.error('导入失败')
      }
    },
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
      //
      const data = this.format(results, header)
      console.log(data, 'data')
      // 发送ajax
      this.doImport(data)
    },
    // 修改格式
    format(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      // （1） 找出所有的中文key
      //  (2)  得到对应的英文key
      //  (3)  拼接一个新对象： 英文key:值
      const res = results.map(zhObj => {
        // obj属性名是中文
        // 1. 取出所有的属性名 ---> 数组
        // 2  循环这个数组
        //    向newObj中补充键值对
        //             键：从中文->英文
        //             值: obj中的值
        const newObj = {}
        const zhKets = Object.keys(zhObj)
        zhKets.forEach(zhKey => {
          const enKey = mapInfo[zhKey]
          // 判断当前的key是否和日期有关,额外进行处理
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            newObj[enKey] = new Date(formatExcelDate(zhObj[zhKey]))
          } else {
            newObj[enKey] = zhObj[zhKey]
            console.log(newObj[enKey], 1231)
          }
        })
        return newObj
      })
      return res
    },

    // 导出
    formatDate(rows) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const enKeys = Object.keys(rows[0])
      const header = enKeys.map(enKey => map[enKey])
      const data = rows.map(obj => {
        return Object.values(obj)
      })
      console.log(enKeys, header, data)
      return {
        header,
        data // [ ['13612345678', '管理员'], [] ]
      }
    },
    async hExport() {
      // 1. 发送请求 获取数据
      const res = await getEmployeeList()
      // 2. 转换格式
      const { header, data } = this.formatDate(res.data.rows)
      console.log('结果', header, data)
      // 3. 导出
      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    }
  }
}
</script>
